﻿namespace MES.Server.Utility.FileMiddleware
{
    public class DownloadImagesMiddleware
    {
        /// <summary>
        /// 中间件之后 下一个要执行的逻辑
        /// </summary>
        private readonly RequestDelegate _next;
        private string? _directoryPath = null;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="next"></param>
        /// <param name="directoryPath"></param>
        public DownloadImagesMiddleware(RequestDelegate next, string directoryPath)
        {
            _next = next;
            _directoryPath = directoryPath;
        }


        /// <summary>
        /// 读取图片信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context)
        {
            if (context.Request.Path.Value!.EndsWith(".jpg")
               || context.Request.Path.Value!.EndsWith(".png"))//规则支持自定义
            {
                //在这里就加载图片返回输出图片的 文件流
                string fileUrl = $"{_directoryPath}{context.Request.Path.Value}";
                if (!File.Exists(fileUrl)) //如果文件不存在就继续往后的流程
                {
                    fileUrl = $"{_directoryPath}/FileUpload/NoImg.jpg";  //返回一个默认的图片
                }

                #region 读取图片的文件流
                context.Request.EnableBuffering();
                context.Request.Body.Position = 0;
                var responseStream = context.Response.Body;

                using (FileStream newStream = new FileStream(fileUrl, FileMode.Open))
                {
                    context.Response.Body = newStream;
                    newStream.Position = 0;

                    var responseReader = new StreamReader(newStream);
                    var responseContent = await responseReader.ReadToEndAsync();
                    newStream.Position = 0;
                    await newStream.CopyToAsync(responseStream);
                    context.Response.Body = responseStream;

                }

                #endregion

            }
            else
            {
                await _next(context);
            }
        }

    }
}
